//
//  TRAddressEditViewController.m
//  WeiMiLan
//
//  Created by anan on 15/8/5.
//  Copyright (c) 2015年 Mac. All rights reserved.
//

#import "TRAddressEditViewController.h"

@interface TRAddressEditViewController ()

@end

@implementation TRAddressEditViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self initNavigation];
    
    if (self.adderssDic) {
        NSString *address = self.adderssDic[@"ADDRESS"];
        NSArray *arr = [address componentsSeparatedByString:@";"];
        if (arr.count==4) {
            self.textFieldName.text = arr[0];
            self.textFieldPhone.text = arr[1];
            [self.buttonSSQ setTitle:arr[2] forState:UIControlStateNormal];
            self.textViewContent.text = arr[3];
        }else{
            [self.textViewContent setText:address];
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initNavigation
{
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    self.weChatNavigationBar=[[WeChatNavigationBar alloc] init];
    [self.view addSubview:self.weChatNavigationBar];
    self.weChatNavigationBar.titleLabel.text=@"编辑收货地址";
    
    [self.weChatNavigationBar.leftButton setImage:[UIImage imageNamed:@"button_nav_back_a"] forState:UIControlStateNormal];
    [self.weChatNavigationBar.leftButton addTarget:self action:@selector(buttonBackAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.weChatNavigationBar.rightButton.hidden = NO;
    [self.weChatNavigationBar.rightButton setTitle:@"保存" forState:UIControlStateNormal];
    self.weChatNavigationBar.rightButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [self.weChatNavigationBar.rightButton sizeToFit];
    [self.weChatNavigationBar.rightButton setImage:nil forState:UIControlStateNormal];
    [self.weChatNavigationBar.rightButton addTarget:self action:@selector(buttonAddAction:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)buttonAddAction:(UIButton*)button {
    if (self.textFieldName.text.length<2) {
        [SVProgressHUD showErrorWithStatus:@"请输入收件人"];
        return;
    }
    if (self.textFieldPhone.text.length<6) {
        [SVProgressHUD showErrorWithStatus:@"请输入电话号码"];
        return;
    }
    if (self.textViewContent.text.length<10) {
        [SVProgressHUD showErrorWithStatus:@"请输入详细地址"];
        return;
    }
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"警告" message:@"请确定收货地址正确无误，必须包括收收件人姓名，电话号码，详细地址三个部分!!!" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
}

- (void)buttonBackAction:(UIButton*)button {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex==1) {
        if (self.adderssDic) {
            [self doEdit];
        }else{
            [self doAdd];
        }
    }
}

- (NSString*)getContent {
    return [NSString stringWithFormat:@"%@;%@;%@;%@",self.textFieldName.text,self.textFieldPhone.text,self.buttonSSQ.titleLabel.text,self.textViewContent.text];
}

- (void)doAdd {
    [QLMaskUtil showMaskLoadingWithView:self.view];
    NSString *URLTmp = @"http://ping.vsmu.cn/app/Interface/UserAddress?type=14002&userId=%@&address=%@";
    URLTmp = [NSString stringWithFormat:URLTmp,ApplicationDelegate.currentUserId,[self getContent]];
    NSString *URLTmp1 = [URLTmp stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];  //转码成UTF-8  否则可能会出现错误
    URLTmp = URLTmp1;
    NSLog(@"%@",URLTmp);
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString: URLTmp]];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        [QLMaskUtil hideLoadingMaskWithView:self.view];
        NSString *requestTmp = [NSString stringWithString:operation.responseString];
        NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableContainers error:nil];
        [self dismissViewControllerAnimated:YES completion:nil];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [QLMaskUtil hideLoadingMaskWithView:self.view];
        NSLog(@"Failure: %@",error);
        [SVProgressHUD showImage:nil status:@"提交失败，请重试"];
    }];
    [operation start];
}

- (void)doEdit {
    [QLMaskUtil showMaskLoadingWithView:self.view];
    NSString *URLTmp = @"http://ping.vsmu.cn/app/Interface/UserAddress?type=14003&address=%@&userId=%@&id=%@";
    URLTmp = [NSString stringWithFormat:URLTmp,[self getContent],ApplicationDelegate.currentUserId,[self.adderssDic ql_stringForKey:@"ID"]];
    NSString *URLTmp1 = [URLTmp stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];  //转码成UTF-8  否则可能会出现错误
    URLTmp = URLTmp1;
    NSLog(@"%@",URLTmp);
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString: URLTmp]];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        [QLMaskUtil hideLoadingMaskWithView:self.view];
        NSString *requestTmp = [NSString stringWithString:operation.responseString];
        NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableContainers error:nil];
        [self dismissViewControllerAnimated:YES completion:nil];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [QLMaskUtil hideLoadingMaskWithView:self.view];
        NSLog(@"Failure: %@",error);
        [SVProgressHUD showImage:nil status:@"提交失败，请重试"];
    }];
    [operation start];
}

#pragma mark - HZAreaPicker delegate
-(void)pickerDidChaneStatus:(HZAreaPickerView *)picker
{
    if (picker.pickerStyle == HZAreaPickerWithStateAndCityAndDistrict) {
        NSString *ssq = [NSString stringWithFormat:@"%@%@%@", picker.locate.state, picker.locate.city, picker.locate.district];
        [self.buttonSSQ setTitle:ssq forState:UIControlStateNormal];
    } else{
        NSString *ssq = [NSString stringWithFormat:@"%@%@", picker.locate.state, picker.locate.city];
        [self.buttonSSQ setTitle:ssq forState:UIControlStateNormal];
    }
}

-(NSArray *)areaPickerData:(HZAreaPickerView *)picker
{
    NSArray *data;
    if (picker.pickerStyle == HZAreaPickerWithStateAndCityAndDistrict) {
        data = [[NSArray alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"area.plist" ofType:nil]];
    } else{
        data = [[NSArray alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"city.plist" ofType:nil]];
    }
    return data;
}

-(void)cancelLocatePicker
{
    [self.pickerView cancelPicker];
    self.pickerView.delegate = nil;
    self.pickerView = nil;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
    [self cancelLocatePicker];
}


- (IBAction)buttonSSQAction:(id)sender {
    [self.textFieldName resignFirstResponder];
    [self.textFieldPhone resignFirstResponder];
    [self.textViewContent resignFirstResponder];
    if (self.pickerView) {
        [self cancelLocatePicker];
    }
    
    self.pickerView = [[HZAreaPickerView alloc] initWithStyle:HZAreaPickerWithStateAndCityAndDistrict
                                                    withDelegate:self
                                                   andDatasource:self];
    [self.pickerView showInView:self.view];
}

@end
